package com.burns.rbac.commons.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.burns.rbac.entity.UserToken;

import java.util.Date;

public class JWTUtils {
    private static final long TOKEN_TIME_OUT = 60 * 30 * 1000;//30分钟
    private static final String USERTOKEN = "token";
    private static final Algorithm TOKENSIGN = Algorithm.HMAC256("Burns");

    /**
     * 创建一个新的token字符串
     *
     * @param userToken 携带用户信息
     * @return
     */
    public static String createToken(UserToken userToken) {
        String userJson = JSON.toJSONString(userToken);
        String token = JWT.create()
                .withClaim(USERTOKEN, userJson)
                .withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_TIME_OUT))
                .sign(TOKENSIGN);
        return token;
    }

    /**
     * 检查token的合法性
     *
     * @param token
     */
    public static DecodedJWT checkToken(String token) throws JWTVerificationException {
        return JWT.require(TOKENSIGN).build().verify(token);
    }

    /**
     * 从token获取用户信息
     *
     * @param token
     * @return
     */
    public static UserToken getUserToken(String token) {
        //1、校验token合法性
        DecodedJWT decodedJWT = checkToken(token);
        //2、解析token获取用户字符串
        String userJson = decodedJWT.getClaim(USERTOKEN).asString();
        //3、转换字符串，返回UserToken
        return JSON.parseObject(userJson, UserToken.class);
    }
}
